package com.dpad.telematicsclientapp.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.View
import com.dpad.crmclientapp.android.modules.newapp.ui.fragment.*
import com.dpad.crmclientapp.android.widget.BottomTabLayout
import com.dpad.telematicsclientapp.android.R
import com.dpad.telematicsclientapp.entity.UserCenterOnclick
import com.dpad.telematicsclientapp.netlibrary.MainApplicaton
import com.dpad.telematicsclientapp.netlibrary.base.basecopy.AppManager
import com.dpad.telematicsclientapp.netlibrary.base.basecopy.BaseCopyActivity
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.OutMessageBean
import com.dpad.telematicsclientapp.presenter.HomePresenter
import com.dpad.telematicsclientapp.service.GetLocalInfoService
import com.dpad.telematicsclientapp.service.PollingUtils
import com.dpad.telematicsclientapp.ui.fragment.TSFXFragment
import com.dpad.telematicsclientapp.util.DataStatisticsUtils
import com.dpad.telematicsclientapp.util.TitleToCode
import com.dpad.telematicsclientapp.util.utils.StatusBarUtil
import com.dpad.telematicsclientapp.util.utils.T
import com.dpad.telematicsclientapp.utils.AppUpdateUtil
import com.dpad.telematicsclientapp.utils.afterLogin
import com.flyco.roundview.RoundTextView
import com.socks.library.KLog
import kotlinx.android.synthetic.main.activity_home.*
import rx.subscriptions.CompositeSubscription

class HomeActivity : BaseCopyActivity<HomePresenter>(), UserCenterOnclick {

    /**
     * 默认选中首页
     */
    private var selectPosition = 2
    /**
     * 记录上次选中的位置
     */
    private var prePosition = 2

    private var tag = 0;
    private lateinit
    var findFragment: Fragment//发现
    private lateinit var messageFragment: Fragment//消息
    private lateinit var homeCenterFragment: Fragment//首页
    private lateinit var tMallFragment: Fragment//商城
    //    private lateinit var userFragment: Fragment//用户
    private lateinit var userCenterDetailFragment: Fragment//详细版
    private lateinit var userCenterNommalFragment: Fragment//普通版

    private lateinit var currentFragment: Fragment
    private lateinit var showFragment: Fragment

    private var fragmentList = arrayListOf<Fragment>()

    private var isDetailFragment: Boolean = false

    //双击back退出间隔
    val DOUBLE_CLICK_EXIT_INTERVAL = 2 * 1000
    //记录上次点击back键时间
    private var mLastBackPressedTime = 0.0

    /**
     * 登录成功后需要跳转的position
     */
    private var loginJumpPosition = 2

    override fun initPageData() {
        StatusBarUtil.transparencyBar(this)
        /**
         * 初始化fragments
         */
        initFragments()
        initDatas()
        bottomTab.selectTab(2)
        /**
         * 底部导航栏点击事件
         */
        MainApplicaton.setNeedShowPinDialog(false)
        //获取定位信息上传服务
        PollingUtils.startPollingService(this, 300, GetLocalInfoService::class.java, GetLocalInfoService.ACTION)
        //检测版本更新
        if (MainApplicaton.isDownIng) {
            T.showToastSafe("正在下载,请稍后!")
            return
        } else {
            AppUpdateUtil.checkVersion(this, true,false)
        }

    }

    private fun initDatas() {
//        initFragments()
        showFragment(selectPosition)
        bottomTab.setOnTabClick(object : BottomTabLayout.OnTabClick {
            override fun onTabSelected(position: Int) {
                if (selectPosition != position) {
                    selectPosition = position
                    showFragment(selectPosition)
                    if (selectPosition == 0) {
                        //DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE115.title, System.currentTimeMillis().toString() + "", Constant.NOMAL))
                    }
                }
            }

            override fun needLogin(position: Int): Boolean {
                loginJumpPosition = position
                return if (position == 1 || position == 3 || position == 4) {
//                    if (MainApplicaton.sIsLogin) {
//                        true
//                    } else {


                    afterLogin {
                        KLog.e("bottomTab", "登录成功后")
                        bottomTab.selectTab(position)
                    }
                    MainApplicaton.sIsLogin
//                        false
//                    }
                } else {
                    true
                }
            }
        })

    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val isLoginSuccess = intent?.getBooleanExtra("loginStatus", false)
        val selectPosition = intent?.getIntExtra("selectPosition", 0)
//        isDetailFragment = false
        initDatas()
        if (isLoginSuccess!!) {
            setLoadingEnable()
            if (loginJumpPosition != 0) {
                bottomTab.selectTab(loginJumpPosition)
            }
        } else {
            /**
             * 跳转到商城
             */
            if (selectPosition == 3) {
                setLoadingEnable()
                bottomTab.selectTab(3)
            } else if (selectPosition == 2) {//跳转到首页
                bottomTab.selectTab(2)
            } else {
                if (loginJumpPosition != 0) {
                    bottomTab.selectTab(2)
//                    bottomTab.selectTab(loginJumpPosition)
                }
            }

        }
        changeBottomVisible(true,"")
    }

    private fun setLoadingEnable() {
        try {
            if (currentFragment is THomeFragment) {
                val tHomeFragment: THomeFragment = currentFragment as THomeFragment
                tHomeFragment.needLoading = false
            }
        } catch (e: java.lang.Exception) {
            KLog.e("HomeActivity", e.toString())
        }
    }

    private fun initFragments() {
        findFragment = TSFXFragment()
        messageFragment = MessageFragment()

        tMallFragment = MallFragment()
        userCenterDetailFragment = UserCenterDetailFragment()
        userCenterNommalFragment = UserCenterFragment()
//        userFragment = userCenterNommalFragment

        fragmentList.clear()
        fragmentList.add(findFragment)
        fragmentList.add(messageFragment)
        homeCenterFragment = THomeFragment() //用户类型（0：T用户，1：非T用户，2：飞车用户）

        fragmentList.add(homeCenterFragment)
        fragmentList.add(tMallFragment)
        fragmentList.add(userCenterNommalFragment)
        fragmentList.add(userCenterDetailFragment)
        currentFragment = fragmentList[2]
    }

    private fun showFragment(position: Int) {
        val transaction = supportFragmentManager.beginTransaction()
        if (position == 3) {
            transaction.remove(tMallFragment)
            fragmentList.remove(tMallFragment)
            tMallFragment = MallFragment()
            fragmentList.add(3, tMallFragment)

        }
        showFragment = if (position == 4) {
            if (isDetailFragment) {
                fragmentList[5]
            } else {
                fragmentList[4]
            }
        } else {
            fragmentList[position]
        }
        if (position != 3) {
            changeBottomVisible(true,"")
        }

//        if (prePosition == 4) {
//            if (userFragment.isAdded && !userFragment.isHidden) {
//                transaction.hide(userFragment)
//            }
//        }
//        if (position == 4) {
//            if (isDetailFragment) {
//                transaction.setCustomAnimations(R.anim.in_right, R.anim.out_right)
//            } else {
//                transaction.setCustomAnimations(R.anim.in_left, R.anim.out_left)
//            }
//        }else{
//            transaction.setCustomAnimations(R.anim.nomal, R.anim.nomal)
//        }
//        if(!flag){
//            closeAnim()
//            flag=true
//        }
        currentFragment = if (!showFragment.isAdded) {
            if (currentFragment.isAdded && !currentFragment.isHidden) {
                transaction.hide(currentFragment)
            }
            transaction.add(R.id.main_frame, showFragment)
            showFragment
        } else {
            transaction.hide(currentFragment)
            transaction.show(showFragment)
            showFragment
        }
        transaction.commit()
        prePosition = position
    }


    override fun getLayout(): Int {
        return R.layout.activity_home
    }

    override fun newPresenter(subscriptions: CompositeSubscription?): HomePresenter? {
        return HomePresenter()
    }

    override fun getPageTitle(): String {
        return TitleToCode.TYPE36.title
    }
    override fun isTActivity(): Boolean {
        return false
    }
    override fun getNeedSetDarkStatusText(): Boolean {
        return false
    }


    /**
     * 退出App, 清空activity
     */
    private fun exitApp() {
        if (System.currentTimeMillis() - mLastBackPressedTime > DOUBLE_CLICK_EXIT_INTERVAL) {
            T.showToastSafe("再次点击退出应用")
            mLastBackPressedTime = System.currentTimeMillis().toDouble()
            try {
                DataStatisticsUtils.startServiceWrite(this)
            } catch (e: Exception) {

            }
        } else {
            PollingUtils.stopPollingService(this, GetLocalInfoService::class.java, GetLocalInfoService.ACTION)
            AppManager.getInstance().exitApp(MainApplicaton.getContext())
        }
    }

    override fun onBackPressed() {

        T.showToastSafe("onBackPressed@@@")
        if (currentFragment is MallFragment) {

            T.showToastSafe("onBackPressed！！！")
            val tmallFragment: MallFragment = currentFragment as MallFragment
            /**
             * 如果可以重定向,则重定向,否则走返回事件
             */
            if (tmallFragment.backPress()) {
                exitApp()
            }
        } else {
            exitApp()
        }
    }

    @SuppressLint("CommitTransaction")
    override fun changeUserCenter(isDetailFragment: Boolean) {
        this.isDetailFragment = isDetailFragment
        showFragment(4)
    }

    fun selectMall() {
        bottomTab.selectTab(3)
    }

    /**
     * 商城改变底部按钮可见
     */
    fun changeBottomVisible(visible: Boolean, url:String) {
        if(!visible&&url.indexOf("https://ntsp.dpca.com.cn/preprod/nev_tmall/#/payFinish?orderNo")!=-1){
            bottomTab.visibility =  View.VISIBLE
            bottom_view.visibility = View.VISIBLE
            return
        }
        if(!visible&&url.indexOf("https://ntsp.dpca.com.cn/nev_tmall/#/payFinish?orderNo")!=-1){
            bottomTab.visibility =  View.VISIBLE
            bottom_view.visibility = View.VISIBLE
            return
        }
        bottomTab.visibility = if (visible) {
            View.VISIBLE
        } else {
            View.GONE
        }
        bottom_view.visibility = if (visible) {
            View.VISIBLE
        } else {
            View.GONE
        }
    }
    fun showPoint(visible: Boolean) {
        var mainmessageicon =  bottomTab.findViewById<RoundTextView>(R.id.mainmessageicon);
        mainmessageicon.visibility = if (visible) {
            View.VISIBLE
        } else {
            View.GONE
        }
    }
    override fun onResume() {
        super.onResume()
        MainApplicaton.setNeedShowPinDialog(false)
        DataStatisticsUtils.startServiceWrite(this)
        if (MainApplicaton.sIsLogin) {
            val map = sortedMapOf(Pair("", "" as Any))
            getP().getMessageData(map)
        }else{
            showPoint(false)
        }
    }
    fun showData(bean: OutMessageBean) {
        for(resultInstance in bean.result){
            if(resultInstance.num>0){
                tag = 1;
            }
        }
        if(tag==1){
            showPoint(true)
        }else{
            showPoint(false)
        }
        tag = 0;
    }

    override fun onPause() {
        super.onPause()
        DataStatisticsUtils.startServiceWrite(this)
    }




}
